from models.fields import CharField, Field
from copy import deepcopy
from storage import storage


class InvalidField(BaseException):
    pass


class Model:
    def __init__(self, **kwargs):
        self.__dict__["_fields"] = {}
        for key, value in kwargs.items():
            setattr(self, key, value)

    def __setattr__(self, key, value):
        if key not in self.__class__.__dict__:
            raise InvalidField(key)

        if key not in self.__dict__["_fields"]:
            v = deepcopy(getattr(self, key))
            self.__dict__["_fields"][key] = v
            self.__dict__[key] = v

        self.__dict__["_fields"][key].value = value
        self.__dict__[key].value = value

    # def __getattr__(self, item):
    #     return self.__dict__["_fields"][item].value

    def save(self):
        data_dict = {}
        for key, value in self._fields.items():
            assert isinstance(value, Field)
            value.is_valid()
            data_dict[key] = value.value

        storage.save(**data_dict)
